package com.cory.boot.component.uploader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 文件下载
 *
 * @author lw
 * @version 1.0
 * @date 2022/2/8 23:30
 */
@Slf4j
@RestController
@RequestMapping("/download")
public class DownloadController {
    
    @GetMapping(value = "/file")
    public void downloadFile(String fileId, String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            File file = UploaderUtils.getFile(fileId);
            log.info("fileId = " + fileId);
            response.setCharacterEncoding("utf-8");
            if(file.exists()) {
                if(fileName.contains("/")) {
                    fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                }
                response.setHeader("Content-Disposition", "attachment;fileName=" + setFileDownloadHeader(request, fileName));
                response.addHeader("Content-Length", "" + file.length());
                response.setContentType("application/binary;charset=ISO8859-1");

                writeBytes(file.getPath(), response.getOutputStream());
            } else {
                response.getWriter().write("<script>alert('文件不存在');</script>");
            }

        }
        catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
    

    /**
     * 文件下载（resource目录下的文件）
     * @param fileName
     * @param response
     * @param request
     */
    @GetMapping(value = "/resource")
    public void downloadResource(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            Resource resource = new ClassPathResource(fileName);
            File file = resource.getFile();
            String filePath = file.getPath();
            log.info("filePath = " + filePath);
            response.setCharacterEncoding("utf-8");
            if(fileIsExists(filePath)) {
                if(fileName.contains("/")) {
                    fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                }
                response.setHeader("Content-Disposition", "attachment;fileName=" + setFileDownloadHeader(request, fileName));
                response.addHeader("Content-Length", "" + file.length());
                response.setContentType("application/binary;charset=ISO8859-1");

                writeBytes(filePath, response.getOutputStream());
            } else {
                response.getWriter().write("<script>alert('文件不存在');</script>");
            }

        }
        catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 判断文件是否存在
     * @param strFile
     * @return
     */
    public boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists()) {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    /**
     * 输出流
     * @param filePath
     * @param os
     * @throws IOException
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }

            fis = new FileInputStream(file);
            byte[] b = new byte[1024];

            int length;
            while((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException var16) {
            throw var16;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException var15) {
                    var15.printStackTrace();
                }
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }

        }

    }

    /**
     * 设置header
     * @param request
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    public String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}
